import { reactive, ref, unref } from "vue"
import { Captcha } from "./Captcha"
const { state, verify, handleDraw, draw } = Captcha()
//导入element-plus 提示框
import { ElMessage } from "element-plus"
//导入路由
import router from "@/router"
//导入axios
import axios from "axios"

export const useLogon = () => {
  const loginForm = ref()
  const userForm = reactive({
    username: "",
    password: "",
    Code: "",
  })

  //点击登录进行验证
  const submitForm = () => {
    const form = unref(loginForm)
    if (!form) return
    //整体表单验证
    form.validate((valid) => {
      if (valid) {
        //检测成功
        // console.log("valid",valid);
        // console.log("用户名", userForm.username)
        // console.log("密码", userForm.password)
        axios
          .post("http://localhost:3000/token", {
            username: userForm.username,
            password: userForm.password,
          })
          .then((res) => {
            // console.log(res);
            const { code, message, token } = res.data
            //判断用户名和密码是否正确
            if (code != 0) {
              // console.log(token);
              ElMessage.error("用户名和密码错误")
              //如果验证不通过,清空input框
              form.resetFields()
              //清空token
              localStorage.setItem("token", "")
            } else {
              //将token添加到本地
              localStorage.setItem("token", token)
              ElMessage({ message, type: "success" })
              //跳转到首页
              router.push("/home")
              //获取id,修改登录状态为在线
              axios
                .get(`http://localhost:3000/ggusers/${userForm.username}`)
                .then((res) => {
                  // console.log(res)
                  const id = res.data.result.user_id
                  const user_name = res.data.result.user_name
                  const user_password = res.data.result.user_password
                  const user_type = res.data.result.user_type
                  const user_other = res.data.result.user_other

                  // console.log(id, user_name, user_type, user_other)
                  axios
                    .put(`http://localhost:3000/ggusers/${id}`, {
                      user_name,
                      user_password,
                      user_type,
                      user_onlinestatus: "1",
                      user_other,
                    })
                    .then((res) => {
                      // console.log(res)
                    })
                })
            }
          })
      } else if (userForm.username == "" || userForm.password == "") {
        ElMessage.error("用户名和密码不能为空")
      } else {
        // 检验不通过
        localStorage.setItem("token", "")
        //单一表单验证(验证码验证)
        form.validateField("Code", (CodeError) => {
          if (!CodeError) {
            ElMessage.error("验证码输入错误")

            userForm.Code = ""
          } else {
            return false
          }
        })
      }
    })
  }

  return { userForm, loginForm, submitForm }
}
